package com.ljd.controller;

import com.ljd.entity.Admin;
import com.ljd.entity.Borrow;
import com.ljd.service.BookService;
import com.ljd.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
    BookService bookService = new BookServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        String method = req.getParameter("method");
        if (method == null) {
            method = "findAllBorrow";
        }
        switch (method) {
            case "findAllBorrow":
                String pageStr = req.getParameter("page");
                Integer page = Integer.parseInt(pageStr);
                //查找待审核的借阅记录
                List<Borrow> list = bookService.findAllBorrowByState(page,0);
                req.setAttribute("list",list);
                req.setAttribute("dataPerPage", 5);
                req.setAttribute("currentPage", page);
                req.setAttribute("pages", bookService.getBorrowPagesCountByState(0));
                req.getRequestDispatcher("admin.jsp").forward(req, resp);
                break;
            case "handle":
                String idStr = req.getParameter("borrowid");
                String stateStr = req.getParameter("state");
                Integer borrowid = Integer.parseInt(idStr);
                Integer state = Integer.parseInt(stateStr);
                bookService.handleBorrow(borrowid, state, admin.getId());
                if(state==1 || state==2){
                    resp.sendRedirect("/admin?page=1");
                } else if(state==3) {
                    resp.sendRedirect("/admin?method=return&page=1");
                }
                break;
            case "return":
                pageStr = req.getParameter("page");
                page = Integer.parseInt(pageStr);
                //查找已借走的借阅记录
                list = bookService.findAllBorrowByState(page,1);
                req.setAttribute("list",list);
                req.setAttribute("dataPerPage", 5);
                req.setAttribute("currentPage", page);
                req.setAttribute("pages", bookService.getBorrowPagesCountByState(1));
                req.getRequestDispatcher("return.jsp").forward(req, resp);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
